<template>
  <basic-container>
    <div id="main" style="width: 800px;height: 600px"></div>
  </basic-container>
</template>

<script>
import * as echarts from 'echarts';
import * as moment from 'moment';

export default {
  name: "echarts-test1",
  data() {
    return {
      data: [],
      option: {
        title: {
          text: 'Dynamic Data & Time Axis'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            params = params[0];
            let date = new Date(params.name);
            return (
                moment(date).format('YYYY/MM/DD HH:mm:ss') + '  ' + params.value[1]
            );
          },
          axisPointer: {
            animation: false
          }
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          },
          boundaryGap: true,
          axisLabel: {
            formatter: function (value){
              return moment(value).format('MM-DD') + '\n' + moment(value).format('HH:mm');
            }
          },
          splitNumber: 8,
          min: new Date('2022/04/15 00:00:00'),
          max: new Date('2022/04/16 00:00:00'),
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          splitLine: {
            show: false
          }
        },
        series: [
          {
            name: 'Fake Data',
            type: 'line',
            showSymbol: false,
          }
        ]
      },
      now: new Date(2022, 4, 15),
      value: Math.random() * 1000,
      myChart: null,
    };
  },
  created() {
  },
  mounted() {
    this.initEcharts();
  },
  methods: {
    initEcharts() {
      let chartDom = document.getElementById('main');
      this.myChart = echarts.init(chartDom);
      this.initTestData();
      this.option.series[0].data = this.data;
      this.myChart.setOption(this.option);
    },
    initTestData() {
      for (let i = 0; i < 10; i++) {
        this.data.push(this.randomData());
      }
      let data = this.data;
      let rd = this.randomData;
      let myChart = this.myChart;
      setInterval(function () {
        for (let i = 0; i < 5; i++) {
          data.shift();
          data.push(rd());
        }
        console.log(data);
        myChart.setOption({
          series: [
            {
              data: data,
            }
          ]
        });
      }, 20000);
    },
    randomData() {
      let dataRate = 20000;
      this.now = new Date(+this.now + dataRate);
      this.value = this.value + Math.random() * 21;
      return {
        name: this.now.toString(),
        value: [[moment(this.now).format('YYYY/MM/DD HH:mm:ss'), Math.round(this.value)]],
      };
    }
  }
};
</script>

<style scoped></style>